package com.ruoyi.system.outto.dto;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicSessionCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ImgUntil;
import com.ruoyi.common.utils.UUIDGenerator;
import com.ruoyi.system.model.dto.ChunkUploadResp;
import com.ruoyi.system.outto.core.LCConstant;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

//交给IOC容器管理
@Component
public class TencentCOSUtil {
    static Path imgUrl;
//    private static String key = "https://xinghe-prod-1316421853.cos.ap-shanghai.myqcloud.com/";
    private static String key = "2023/11/06/1699257751609.jpg";
    //上传的存储桶的地域，可参考根路径https://qq-test-1303******.cos.地域.myqcloud.com,此参数在COS的后台能查询。
    private static String region = "ap-shanghai";
    //存储桶的名字，是自己在存储空间自己创建的，我创建的名字是：qq-test-1303******
    private static String bucketName = "xinghe-prod-1316421853";

    public static void main(String[] args) {
        // 调用 COS 接口之前必须保证本进程存在一个 COSClient 实例，如果没有则创建
// 详细代码参见本页：简单操作 -> 创建 COSClient
        COSClient cosClient = createCOSClient();


// 存储桶的命名格式为 BucketName-APPID，此处填写的存储桶名称必须为此格式
//        String bucketName = "examplebucket-1250000000";
// 对象键(Key)是对象在存储桶中的唯一标识。
//        String key = "exampleobject";
// 本地文件路径
        try {
            URL url = new URL(LCConstant.defaultImg);
            BufferedImage image = ImageIO.read(url.openStream());
            byte[] bytes = ImgUntil.bufferedImageToByteArray(image);
            File file = convert(bytes);
            String datePath = DateUtils.dateTimeNow("yyyy/MM/dd");
            String key = datePath+"/"+ UUIDGenerator.generate12().substring(0,13)+".jpg";
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
//            System.out.println(putObjectResult.getRequestId());
            ChunkUploadResp chunkUploadResp = ChunkUploadResp.builder()
                    .etag(putObjectResult.getETag()).build();
            System.out.println("https://xinghe-prod-1316421853.cos.ap-shanghai.myqcloud.com/"+key);
        }catch (Exception r){

        }
        cosClient.shutdown();
    }

    public static String uploadImg(String imgUrl){
        COSClient cosClient = createCOSClient();

        try {
            URL url = new URL(imgUrl);
            BufferedImage image = ImageIO.read(url.openStream());
            byte[] bytes = ImgUntil.bufferedImageToByteArray(image);
            File file = convert(bytes);
            String datePath = DateUtils.dateTimeNow("yyyy/MM/dd");
            String s = UUIDGenerator.generate12();
            s= s.substring(s.length()-13,s.length());
            String key = datePath+"/"+ s+".jpg";
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
//            System.out.println(putObjectResult.getRequestId());
            ChunkUploadResp chunkUploadResp = ChunkUploadResp.builder()
                    .etag(putObjectResult.getETag()).build();
            Thread.sleep(200l);
            file.deleteOnExit();
//            System.out.println("https://xinghe-prod-1316421853.cos.ap-shanghai.myqcloud.com/"+key);
            return "https://xinghe-prod-1316421853.cos.ap-shanghai.myqcloud.com/"+key;
        }catch (Exception r){

        }
        cosClient.shutdown();
        return null;
    }

    public static File convert(byte[] byteArray) throws IOException {
        File file = File.createTempFile("kankantemp", ".jpg");
//        imgUrl = file.getPath();
        Path path = Paths.get(file.getAbsolutePath());
        imgUrl = path;
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(byteArray);
        }catch (Exception e){

        }
        return file;
    }

    // 创建 COSClient 实例，这个实例用来后续调用请求
    static COSClient createCOSClient() {
        // 这里需要已经获取到临时密钥的结果。
        // 临时密钥的生成参见 https://cloud.tencent.com/document/product/436/14048#cos-sts-sdk
        String s = cosImg();
        String access = JSONObject.parseObject(s).getString("access");
        String secret = JSONObject.parseObject(s).getString("secret");
        String sessionToken = JSONObject.parseObject(s).getString("sessionToken");
        String tmpSecretId = access;
        String tmpSecretKey = secret;


        COSCredentials cred = new BasicSessionCredentials(tmpSecretId, tmpSecretKey, sessionToken);


        // ClientConfig 中包含了后续请求 COS 的客户端设置：
        ClientConfig clientConfig = new ClientConfig();


        // 设置 bucket 的地域
        // COS_REGION 请参见 https://cloud.tencent.com/document/product/436/6224
        clientConfig.setRegion(new Region(region));


        // 设置请求协议, http 或者 https
        // 5.6.53 及更低的版本，建议设置使用 https 协议
        // 5.6.54 及更高版本，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);


        // 以下的设置，是可选的：


        // 设置 socket 读取超时，默认 30s
        clientConfig.setSocketTimeout(30*1000);
        // 设置建立连接超时，默认 30s
        clientConfig.setConnectionTimeout(30*1000);


        // 如果需要的话，设置 http 代理，ip 以及 port
//        clientConfig.setHttpProxyIp("httpProxyIp");
//        clientConfig.setHttpProxyPort(80);


        // 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }

    public static String cosImg() {
        String url = "http://101.43.52.41:8083/v2/open/tencent/cos/img";
        Map<String, Object> header = new HashMap<>();
        String originalText = "mucRvmJU:3mVAGMUXG39MHkaC9pdvPGEf49RPYRAP";
        byte[] encodedBytes = Base64.getEncoder().encode(originalText.getBytes()); // 对字符串进行编码
        String encryptedText = new String(encodedBytes);
        System.out.println(encryptedText);
        header.put("Authorization","xinghe-server "+encryptedText);
        String response = HttpRequest.get(url).header("Authorization","xinghe-server "+encryptedText).execute().body();

        return response;
    }
}